<?php

header('content-type:application:json;charset=utf-8');
header('Access-Control-Allow-Origin:*');  
header('Access-Control-Allow-Methods:POST');  
header('Access-Control-Allow-Headers:x-requested-with,content-type'); 


include("lib/cls_mysql.php");
include("lib/cls_image.php");
include('lib/config.php');

$db = new cls_mysql($cfg['host'], $cfg['user'], $cfg['pwd'],$cfg['database']);
if(!$db){
	die('mysql no connection');
}

$mark = isset($_REQUEST['mark'])?$_REQUEST['mark']:'';
$size = isset($_REQUEST['size'])?$_REQUEST['size']:'';

if(empty($mark)){
	die('Params Error');
}



$sql = "select * from {$cfg['table']} where token='{$mark}' limit 1";
$row = $db->getRow($sql);

//var_dump($row);

$image = new cls_image();


//header("Content-type: image/jpeg");   
if(!empty($size)){
	$fg = explode('x',$size);
	if(count($fg)<2){
		$wid = intval($fg[0]);
		if($wid>0){
			$hei = $wid;
		}
		else{
			create_img($row['path']);
		}
	}
	else{
		$wid = intval($fg[0]);
		$hei = intval($fg[1]);
	}
	
	if($wid>2040 || $hei>2040){
		die('大小不能超过2040像素');
	}
	
	$image->make_thumb($row['path'],$wid,$hei);
}
else{
	create_img($row['path']);
}

function create_img($path){

	$info = getimagesize($path);
	$mime = isset($info['mime'])?$info['mime']:'';
	if(!$mime){
		$ext = substr(strrchr($path,'.'),1); 
		if($ext=='jpg'){
			$image = imagecreatefromjpeg($path);
			imagejpeg($image);  
		}
		elseif($ext=='png'){
			$image = imagecreatefrompng($path);
			imagepng($image);  
		}
		elseif($ext=='gif'){
			$image = imagecreatefromgif($path);
			imagegif($image);  
		}
		else{
			die('create image fail');
			return false;
		}
	}
	
	$image = img_resource($path,$mime);
	imagedestroy($image);
	$image = null;
}



/**
 * 根据来源文件的文件类型创建一个图像操作的标识符
 *
 * @access  public
 * @param   string      $img_file   图片文件的路径
 * @param   string      $mime_type  图片文件的文件类型
 * @return  resource    如果成功则返回图像操作标志符，反之则返回错误代码
 */
function img_resource($img_file, $mime_type)
{
	switch ($mime_type)
	{
		case 1:
		case 'image/gif':
			$res = imagecreatefromgif($img_file);
			imagegif($res);  
			break;

		case 2:
		case 'image/pjpeg':
		case 'image/jpeg':
			$res = imagecreatefromjpeg($img_file);
			imagejpeg($res);  
			break;

		case 3:
		case 'image/x-png':
		case 'image/png':
			
			$res = imagecreatefrompng($img_file);
			imagesavealpha($res, true);
			imagepng($res);
			break;

		default:
			return false;
	}

	return $res;
}